<template>
  <div>
    <div>
      <el-form :inline="true" style="margin: 20px">
        <el-form-item label="角色名称:">
          <el-input v-model="queryParam.name" placeholder="请输入角色名称查询" clearable />
        </el-form-item>
        <el-button type="primary" @click="searchQuery">查询</el-button>
        <el-button @click="searchReset">重置</el-button>
      </el-form>
    </div>
    <div>
      <el-button
        type="primary"
        icon="el-icon-plus"
        style="position:relative;left:20px;top:-25px"
        @click="handleAdd"
      >新增</el-button>

      <el-dropdown style="position:relative;left:30px;top:-25px">
        <el-button>
          批量操作<i class="el-icon-arrow-down el-icon--right" />
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item icon="el-icon-delete" @click.native="batchDel">删除</el-dropdown-item>
          <el-dropdown-item icon="el-icon-success" @click.native="batchSetStatus('true')">启用</el-dropdown-item>
          <el-dropdown-item icon="el-icon-error" @click.native="batchSetStatus('false')">禁用</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <div class="table">
      <!-- table区域 -->
      <el-table
        ref="multipleTable"
        :data="roleList"
        tooltip-effect="dark"
        border
        style="width: 97%;margin:10px;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center" width="120px" />
        <el-table-column prop="id" label="#" align="center" />
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="type" label="数据类型" />
        <el-table-column prop="priceLimit" label="价格屏蔽" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="sort" label="排序" />
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.enabled" type="success">启动</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="240px">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-s-tools" @click="allocationFunction(scope.row)">分配权限</el-button>
            <!-- 分配功能 -->
            <el-dialog title="分配权限" :visible.sync="dialogFunction">
              <div ref="container">
                <div class="drawer-bootom-button">
                  <el-dropdown style="position:relative;right: 300px;top: -10px;">
                    <el-button>
                      树操作 <i class="el-icon-bottom"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item key="1" @click.native="selectParent">父子关联</el-dropdown-item>
                      <el-dropdown-item key="2" @click.native="canleGuanLian">取消关联</el-dropdown-item>
                      <el-dropdown-item key="3" @click.native="selectAllNodes">全部勾选</el-dropdown-item>
                      <el-dropdown-item key="4" @click.native="clearAllNodes">取消全选</el-dropdown-item>
                      <el-dropdown-item key="5" @click.native="unFoldAll2(menuOptions)">展开所有</el-dropdown-item>
                      <el-dropdown-item key="6" @click.native="collapseAll2(menuOptions)">合并所有</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
                <template>
                  <el-tree
                    style="margin-left: 20px;"
                    ref="tree"
                    class="tree-border"
                    :data="menuOptions"
                    :expand-on-click-node="false"
                    :check-strictly="checkStrictly"
                    show-checkbox
                    node-key="id"
                    empty-text="加载中，请稍候"
                    :props="defaultProps"
                  />
                </template>
              </div>
              <div style="margin-left: 540px;">
                <el-button @click="dialogFunction = false">取消</el-button>
                <el-button @click="getCheckedNodes" type="primary">确定</el-button>
              </div>
            </el-dialog>
            <el-button type="text" icon="el-icon-edit" @click="edit(scope.row)">编辑</el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              style="color: red;"
              @click="removeById(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="float: right;margin-right: 40px;margin-top: 5px;"
        :current-page="current"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <div>
      <!-- Form -->
      <el-dialog :title.sync="dialogTitle" :visible.sync="dialogFormVisible">
        <el-form ref="form" :model="form" :rules="rules" :label-position="right" label-width="120px">
          <el-form-item label="角色名称:" prop="name">
            <el-input v-model="form.name" style="width:500px" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="数据类型:" prop="type">
            <el-select v-model="form.type" placeholder="请选择数据类型" style="width:500px">
              <el-option label="全部数据" value="全部数据" />
              <el-option label="本机构数据" value="本机构数据" />
              <el-option label="个人数据" value="个人数据" />
            </el-select>
            <span style="padding-left:20px">
              <el-tooltip placement="top">
                <div slot="content" style="height:90px;width:250px">
                  1、全部数据-该角色对应的用户可以看到全部单据；
                  2、本机构数据-该角色对应的用户可以看到自己所在机构的全部单据；
                  3、个人数据-该角色对应的用户只可以看到自己的单据。单据是指采购入库、销售出库等
                </div>
                <!-- elementui图标库：显示黑色的问号图标   -->
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
          </el-form-item>
          <el-form-item label="价格屏蔽:">
            <el-select v-model="form.priceLimit" placeholder="请选择价格屏蔽" style="width:500px">
              <el-option label="屏蔽采购价" value="屏蔽采购价" />
              <el-option label="屏蔽零售价" value="屏蔽零售价" />
              <el-option label="屏蔽销售价" value="屏蔽销售价" />
            </el-select>
            <span style="padding-left:20px">
              <el-tooltip placement="top">
                <div slot="content" style="height:40px;width:250px">
                  价格屏蔽支持多选，主要用于控制首页界面和物料的价格屏蔽
                </div>
                <!-- elementui图标库：显示黑色的问号图标   -->
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
          </el-form-item>
          <el-form-item label="描述:">
            <el-input v-model="form.description" type="textarea" placeholder="请输入描述" style="width:500px" />
          </el-form-item>
          <el-form-item label="排序:">
            <el-input v-model="form.sort" style="width:500px" placeholder="请输入排序" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false; form = {}">取 消</el-button>
          <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import roleApi from '@/api/role'
import functionApi from '@/api/function'

export default {
  data() {
    return {
      activeIndex: '1',
      // 查询条件
      queryParam: {
        name: undefined
      },
      form: {
        id: undefined,
        name: undefined,
        type: undefined,
        priceLimit: undefined,
        description: undefined,
        sort: undefined
      },
      menuOptions: [],
      defaultProps: {
        children: 'children',
        label: 'menuName',
        id: 'id'
      },
      checkParam: {
        id: '',
        name: undefined
      },
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' },
          { validator: this.checkIsNameExist, trigger: 'blur' }],
        type: [{ required: true, message: '请选择数据类型', trigger: 'blur' }]
      },
      roleList: [],
      multipleSelection: [],
      current: 1,
      pageSize: 5,
      total: 0,
      priceLimit: '',
      dialogFormVisible: false,
      dialogTitle: '',
      dialogFunction: false,
      checkStrictly: false, //是否父子联动
      functionIds: [], //功能集合
      roleId: '',
    }
  },
  created() {
    this.list()
  },
  methods: {
    // 全部展开
    unFoldAll2(data) {
      let self = this;
      data.forEach((el) => {
        self.$refs.tree.store.nodesMap[el.id].expanded = true;
        el.children && el.children.length > 0
          ? self.unFoldAll2(el.children)
          : ""; // 子级递归
      });
    },
    // 全部折叠
    collapseAll2(data) {
      let self = this;
      data.forEach((el) => {
        self.$refs.tree.store.nodesMap[el.id].expanded = false;
        el.children && el.children.length > 0
          ? self.collapseAll2(el.children)
          : ""; // 子级递归
      });
    },
    getCheckedNodes() {
      //选中的节点编号
      this.functionIds = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys())
      //添加角色的权限信息
      roleApi.addRoleAndFunction(this.functionIds,this.roleId)
        .then(res => {
          this.$message({
              type: 'success',
              message: '操作成功'
          })
          this.list()
          this.$refs.tree.setCheckedKeys([])
          this.dialogFunction = false
        })
    },
    // 列表
    list() {
      roleApi.listRole(this.current, this.pageSize, this.queryParam).then((res) => {
        this.roleList = res.data.records
        this.pageSize = res.data.size
        this.current = res.data.current
        this.total = res.data.total
      })
    },
    // 分配功能
    allocationFunction(row) {
      this.roleId = row.id
      functionApi.functionList()
        .then(res => {
          this.menuOptions = res.data
        })
      functionApi.functionByRoleId(row.id)
        .then(res => {
          const ids = res.data.map(v => v.id)
          this.$refs.tree.setCheckedKeys(ids)
        })
      this.dialogFunction = true
    },
    // 打开新增框
    handleAdd() {
      this.dialogFormVisible = true
      this.dialogTitle = '新增'
      this.form.id = undefined
      this.form = {}
      // // 清除自动触发的表单验证
      // this.$nextTick(() => {
      //   this.$refs['form'].clearValidate()
      // })
    },
    // 分页
    handleSizeChange(val) {
      this.pageSize = val
      this.list()
    },
    handleCurrentChange(val) {
      this.current = val
      this.list()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    searchQuery() {
      this.list()
    },
    searchReset() {
      this.queryParam = {
        name: ''
      }
    },
    batchDel() {
      if (this.multipleSelection === '') {
        this.$message.warning('请至少选择一条数据进行删除！')
      } else {
        this.$confirm('此操作将永久删除该权限，是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          // 声明空数组,这里的数组是后端需要的数据
          const arrray = []
          // 遍历勾选数据取自己需要的id等这里是和后端需要的参数对应
          for (let i = 0; i < this.multipleSelection.length; i++) {
            arrray.push(this.multipleSelection[i].id)// 把取出的对象push到数组里
          }
          roleApi.deleteBatch(arrray).then(res => { // 接口
            this.$message({
                type: 'success',
                message: '操作成功'
            })
            this.list()// 删完成功后初始化查询列表
          })
        })
      }
    },
    batchSetStatus(status) {
      if (this.multipleSelection === '') {
        this.$message.warning('请至少选择一条数据进行修改！')
      } else {
        this.$confirm('是否修改客户状态?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const arrray = []
          // 遍历勾选数据取自己需要的id等这里是和后端需要的参数对应
          for (let i = 0; i < this.multipleSelection.length; i++) {
            arrray.push(this.multipleSelection[i].id)// 把取出的对象push到数组里
          }
          roleApi.batchSetStatus(arrray, status)
            .then(res => {
              this.$message({
                type: 'success',
                message: '修改成功!'
              })
              this.list()
            })
        })
      }
    },
    checkIsNameExist(rule, value, callback) {
      this.checkParam = {}
      this.checkParam.id = this.form.id
      this.checkParam.name = this.form.name
      roleApi.checkIsNameExist(this.checkParam)
        .then(res => {
          if (res.status) {
            callback(new Error('名称已存在'))
          } else {
            console.log(1)
            callback()
          }
        })
    },
    submitForm(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          if (this.form.id === undefined) {
            roleApi.addRole(this.form)
              .then(res => {
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.form = {}
                this.dialogFormVisible = false
                this.list()
              })
          } else {
            roleApi.updateRole(this.form)
              .then(res => {
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
                this.form = {}
                this.dialogFormVisible = false
                this.list()
              })
          }
        }
      })
    },
    // 查看详细
    edit(row) {
      this.dialogTitle = '修改'
      this.dialogFormVisible = true
      this.form = JSON.parse(JSON.stringify(row))
      // // 清除自动触发的表单验证
      // this.$nextTick(() => {
      //   this.$refs['form'].clearValidate()
      // })
    },
    removeById(row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        roleApi.deleteById(row.id)
          .then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.list()
          })
      })
    },
    // 全选
    selectAllNodes(){
      this.$refs.tree.setCheckedNodes(this.menuOptions)
    },
    // 清空
    clearAllNodes(){
      this.$refs.tree.setCheckedKeys([])
    },
    //取消关联
    canleGuanLian(){
      this.checkStrictly = true
    },
    //父子联动
    selectParent(){
      this.checkStrictly = false
    }
  }
}
</script>

<style>
.table {
  position: relative;
  left: 20px;
}
</style>
